
import { InputElement } from '@dom-native/ui';
import { append, getAttr, html, on, setAttr } from 'dom-native';


/**
 * c-password custom element encapsulate a label/input field group ()`c-password > label, input, <span class="unit">`) structure. 
 * component styles are global but scoped via css naming (see c-password.pcss). 
 * 
 * Usage: `<c-password name="fieldNameA" value="value A" unit="Kg"></c-password>`
 * See:  http://localhost:8080/_spec/controls
 * 
 * Attributes: 
 *   - See InputFieldElement.
 * 
 * Properties: 
 *   - See InputFieldElement.
 * 
 * CSS:
 *   - See InputFieldElement.
 * 
 * Content:
 *   - none
 * 
 * Events:
 *   - `CHANGE` see InputFieldElement.
 * 
 */

export class PasswordElement extends InputElement {

	iconHolderEl?: HTMLElement;

	static get observedAttributes() { return InputElement.observedAttributes.concat(['security', 'mode']) }

	set mode(v: string) {
		setAttr(this, "mode", v);
		this.refresh();
	}

	get mode() {
		const m = getAttr(this, "mode");
		return m && m == "security" ? "security" : "password";
	}

	set password(v: boolean) {
		setAttr(this, "password", v);
		this.refresh();
	}

	get password() {
		return this.hasAttribute("password") ? true : false;
	}

	set security(v: boolean) {
		setAttr(this, "security", v);
		this.refresh();
	}

	get security() {
		return this.hasAttribute("security") ? true : false;
	}

	//#region    ---------- Lifecycle ---------- 
	// Component initialization (will be called once by BaseHTMLElement on first connectedCallback)
	init() {
		super.init();
		setAttr(this.inputEl, "type", "text");
		const fragEl = html(`<span class="ico-holder"></span>`);
		[this.iconHolderEl] = append(this, fragEl)!;

		// set value by default
		if (this.mode == "security") {
			this.security = this.security;
		} else {
			this.password = this.password;
		}
		this.refresh();

		on(this, "click", ".ico-holder", (evt) => {
			if (this.mode == "security") {
				this.security = !this.security;
			} else {
				this.password = !this.password;
			}
		});
	}


	refresh() {
		const mode = this.mode;

		if (mode == "security") {
			this.renderIcon(!this.security);
		} else {
			if (this.password) {
				setAttr(this.inputEl, "type", "password");
			} else {
				setAttr(this.inputEl, "type", "text");
			}
			this.renderIcon(!this.password);
		}
	}

	renderIcon(show: boolean) {
		if (show) {
			this.iconHolderEl!.innerHTML = `<d-ico name="ico-see"></d-ico>`;
		} else {
			this.iconHolderEl!.innerHTML = `<d-ico name="ico-cannot-see"></d-ico>`;
		}
	}

	//#endregion ---------- /Lifecycle ---------- 

}


customElements.define("c-password", PasswordElement);
